package org.wevil.thread;

import org.wevil.props.SocketProp;
import org.wevil.util.BeanUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 姜智飞RTU-阀门-监听
 *
 * @since 2022/3/7
 * */
public class SocketListener extends Thread{
    /**
     * 线程名称
     */
    final private static String threadName = "姜智飞RTU监听线程";

    /**
     * 启动项目时开启线程
     */
    @Override
    public void run() {
        ServerSocket ss = null;
        try {
            SocketProp socketProp = BeanUtil.getBean(SocketProp.class);
            // 多线程监听
            int counter = 1;
            ss = new ServerSocket(socketProp.getPort());
            while (!Thread.currentThread().isInterrupted()) {
                Socket socket = ss.accept();
                // 连接超时
                socket.setSoTimeout(10 * 1000 * 60);
                counter++;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentDate = sdf.format(new Date(System.currentTimeMillis()));
                System.out.println(currentDate + ",接收到新连接" + socket.getInetAddress() + ":" + socket.getPort()
                        + "/" + threadName + "[" + counter + "]");
                Thread t = new SocketThread(socket, threadName + "[" + counter + "]");
                // 保存当前对象
                ThreadUtils.rtuSendThreadMap.put(t.getId(), t);
                t.start();
            }
        } catch (IOException ioe) {
            try {
                if(ss != null){
                    ss.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            ioe.printStackTrace();
        }
    }
}
